﻿using AnQinFrameWorkAPI.DataBase;
using AnQinFrameWorkAPI.Entity.Blog.DTO.BlogProjectCase;
using AnQinFrameWorkAPI.Entity.Blog.Entity;
using AnQinFrameWorkAPI.Entity.Blog.View.BlogProjectCase;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using FrameWork.DataHelper;
using FrameWork.Entity;
using FrameWork.Request;
using Microsoft.EntityFrameworkCore;

namespace AnQinFrameWorkAPI.Service.Blog;

/// <summary>
///     项目案例服务
/// </summary>
public class BlogProjectCaseService
{
    private readonly DatabaseContext _context;
    private readonly IMapper _mapper;

    /// <summary>
    ///     构造函数（依赖注入）
    /// </summary>
    public BlogProjectCaseService(DatabaseContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    #region 获取项目案例列表（分页）

    /// <summary>
    ///     获取项目案例列表（分页）
    /// </summary>
    public async Task<RequestResponseModel> GetBlogProjectCaseList(BlogProjectCaseSearchDTO searchDTO)
    {
        // 构建基础查询
        var query = _context.BlogProjectCase
            .ProjectTo<BlogProjectCaseView>(_mapper.ConfigurationProvider)
            .AsNoTracking()
            .WhereIF(a => a.Code.Contains(searchDTO.Code), !string.IsNullOrEmpty(searchDTO.Code))
            .WhereIF(a => a.Name.Contains(searchDTO.Name), !string.IsNullOrEmpty(searchDTO.Name))
            .WhereIF(a => a.CreateTime > searchDTO.StartTime, searchDTO.StartTime != null)
            .WhereIF(a => a.CreateTime < searchDTO.EndTime, searchDTO.EndTime != null);

        // 获取分页数据
        var list = await query
            .OrderByDescending(a => a.CreateTime)
            .Page(searchDTO.PageIndex, searchDTO.PageSize)
            .ToListAsync();

        // 获取总数
        var totalCount = await query.CountAsync();

        // 返回分页结果
        return RequestResponse.OK(new PageResult<BlogProjectCaseView>(list, totalCount), "查询成功");
    }

    #endregion

    #region 新增项目案例

    /// <summary>
    ///     新增项目案例
    /// </summary>
    public async Task<RequestResponseModel> AddBlogProjectCase(BlogProjectCaseAddDTO addDTO)
    {
        // 映射到实体模型
        var entity = _mapper.Map<BlogProjectCaseModel>(addDTO);

        // 设置默认值
        entity.Id = Guid.NewGuid();
        entity.CreateTime = DateTime.Now;

        // 添加到数据库
        _context.BlogProjectCase.Add(entity);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(entity.Id, "新增成功");
    }

    #endregion

    #region 更新项目案例

    /// <summary>
    ///     更新项目案例
    /// </summary>
    public async Task<RequestResponseModel> PutBlogProjectCase(BlogProjectCaseUpdateDTO updateDTO)
    {
        // 验证ID有效性
        var existing = await Valid.ValidId(_context.BlogProjectCase, updateDTO.Id);
        if (existing == null) return RequestResponse.ErrorRequest("项目案例ID无效");

        // 更新实体数据
        _mapper.Map(updateDTO, existing);

        // 保存到数据库
        _context.BlogProjectCase.Update(existing);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(updateDTO.Id, "更新成功");
    }

    #endregion

    #region 删除项目案例

    /// <summary>
    ///     删除项目案例
    /// </summary>
    public async Task<RequestResponseModel> DeleteBlogProjectCase(SingleIdDTO deleteDTO)
    {
        // 验证ID有效性
        var entity = await Valid.ValidId(_context.BlogProjectCase, deleteDTO.Id);
        if (entity == null) return RequestResponse.ErrorRequest("项目案例ID无效");

        // 执行删除
        _context.BlogProjectCase.Remove(entity);
        await _context.SaveChangesAsync();

        return RequestResponse.OK(deleteDTO.Id, "删除成功");
    }

    #endregion
}